import json
import datetime


class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S")
        else:
            return json.JSONEncoder.default(self, obj)


class JsonData:
    def __init__(self):
        self.code = "500"
        self.msg = "Not Set Any Value"
        self.data = []

    # 表示服务器已成功处理了请求
    def success(self):
        self.code = "200"
        self.msg = "ok"
        self.data = []
        return self.to_json()

    # 表示服务器已成功处理了请求，并且返回数据
    def success_data(self, msg="ok", data=[]):
        self.code = "200"
        self.msg = msg
        self.data = data
        return self.to_json()

    # 请求格式错误，或者其它不可知错误，自定义错误码以及提示内容和数据
    def error(self, code, msg="An error has occurred", data=[]):
        self.code = code
        self.msg = msg
        self.data = data
        return self.to_json()

    def to_json(self):
        return json.dumps(
                {"code": self.code,
                 "msg": self.msg,
                 'data': self.data}, ensure_ascii=False, cls=DateEncoder
                )


